import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    CartList:JSON.parse(localStorage.getItem('Cart')) || [],//购物车数组
    result:[],//全选反选
  },
  getters:{
    total(state){
      var total = 0
      state.result.forEach(element=>{
        total+=element.num*element.salePrice
      })
      return total
    }
  },
  mutations: {
    onclick(state,item){
      var Cart = false
      state.CartList.forEach(element=>{
        if(item.productId === element.productId){
          element.num++
          Cart = true
          return
        }
      })
        if(Cart === false){
          state.CartList.push({
            ...item,
            num:1,
            check:false
          })
        }
        console.log(state.CartList);
        localStorage.Cart = JSON.stringify(state.CartList)
    },
    ONCLICK(state,checked){
      if(checked){
        state.result = state.CartList
      }else{
        state.result = []
      }
    },
    DEL(state,index){
      let id = state.CartList.splice(index,1)
      state.result.forEach((element,index)=>{
        if(element._id == id[0]._id){
          state.result.splice(index,1)
        }
      })
      localStorage.Cart = JSON.stringify(state.CartList)
    }
  },
  actions: {
    onclick(context,item){
      context.commit('onclick',item)
    },
    ONCLICK(context,checked){
      context.commit('ONCLICK',checked)
    },
    DEL(context,index){
      context.commit('DEL',index)
    }
  },
  modules: {
  }
})
